<?php
// +‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
// | NewThink [ Think More,Think Better! ]
// +‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
// | 版权所有：山西创泰网络科技有限公司
// +‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
// | Author: lk Date:2019/7/31 Time:9:30
// +‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐

namespace app\api\controller;

use app\common\model\control\ControlStepTwoGetDrainEmissionsModel;
use app\common\model\control\ControlStepTwoGetFacilityParamsModel;
use app\common\service\companyIndustry\industrymodel\TsinghuaDrainEmissionToFacilityParam;
use app\common\service\CompanyService;
use app\common\service\ControlEmissionService;
use app\common\service\ControlService;
use app\common\service\EmissionService;
use app\common\service\companyIndustry\realtime\{
    SulfurPumpService, SulfurSlurrySupplyService, SulfurCaSRatioService, SulfurLiquidGasRatioService
};
use app\common\service\InletFlueGasService;
use app\common\service\WorkingModelService;
use think\Db;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

class ControlTwo extends BaseController
{
    /**
     * 获取公司的排放量
     * 备注：因查询慢，自动入库，并从数据库中查询
     * @author hongwei 2019-09-08
     */
    public function getCompanyEmissions()
    {
        //step1:传参
        $param            = $this->request->param();
        $controlModeId    = isset($param['control_mode_id']) ? $param['control_mode_id'] : 1;  //类型,默认为工业减排
        $type             = isset($param['type']) ? strtoupper($param['type']) : 'SO2';  //类型
        $planNumber       = $param['plan_number'];  //预案编号
        $tsinghuaPlanName = $param['tsinghua_plan_name']; //清华预案名称

        //step2:查询
        $where = [
            'plan_number' => $planNumber,
            'control_mode_id' => $controlModeId,
            'tsinghua_plan_name' => $tsinghuaPlanName,
            'type' => $type,
        ];
        $data  = db::name('control_step_two_get_drain_emissions')
            ->field('*')
            ->where($where)
            ->select();
        if (empty($data)) {
            $this->error('没有数据');
        }
        $this->success('获取数据成功！', $data);

    }

    /**
     * 获取公司的排放量
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-06-24
     */
    public function getCompanyEmissionsAuto()
    {
        ini_set('memory_limit', -1);
        $control         = new ControlService();
        $stepTwoModel    = new ControlStepTwoGetDrainEmissionsModel();
        $controlEmission = new ControlEmissionService();

        //step1:发现清单
        $planNumber = $control->getControlPlanNumber();  //获取今天的预案编号
//        $planList = [
//            'CZ2019-08-23 001号',
//            'CZ2019-08-22 001号',
//            'CZ2019-08-21 001号',
//            'CZ2019-08-20 001号',
//            'CZ2019-08-16 001号',
//            'CZ2019-08-15 001号',
//            'CZ2019-08-14 001号',
//            'CZ2019-08-13 001号',
//            'CZ2019-08-12 001号',
//            'CZ2019-08-10 001号',
//            'CZ2019-08-09 001号',
//            'CZ2019-08-08 001号',
//            'CZ2019-08-06 001号',
//            'CZ2019-08-02 001号',
//            'CZ2019-07-31 001号',
//        ];
//        foreach ($planList as $kk => $vv) {
//            $planNumber = $vv;

            $existSettingList = $control->findSettingList($planNumber);
            if ($existSettingList == false) {
                return false;
            }

            //step3:获取企业的减排前和方案值的排放量
            $tsinghuaPlanNameList = $control->getPlanTsingNameList($planNumber);
            try {
                foreach ($tsinghuaPlanNameList as $k => $v) {
                    //step3-1:发现已经有数据
                    $findStepTwoHaveData = $control->findControlStepTwoGetDrainEmissions($planNumber, $v['name']);
                    if ($findStepTwoHaveData == true) {
                        continue;
                    }
                    if ($findStepTwoHaveData == false) {
                        //step3-2:发现清华的数据,有数据执行，没数据不执行
                        $tsinghuaHaveData = $control->findTsinghuaGetDrainEmissions($planNumber, $v['name']);
                        if ($tsinghuaHaveData == true) {
                            //添加so2入库
                            $so2Emissions = $controlEmission->getTsinghuaCompanyEmission('SO2', 1, $planNumber, $v['name'], 'kg');
                            $stepTwoModel->saveAll($so2Emissions);
                            unset($so2Emissions);
                            //添加no2入入库
                            $no2Emissions = $controlEmission->getTsinghuaCompanyEmission('NO2', 1, $planNumber, $v['name'], 'kg');
                            $stepTwoModel->saveAll($no2Emissions);
                            unset($no2Emissions);
                            print "插入数据成功！";
                        } else {
                            return false;
                        }
                    }
                }

            } catch (\Exception $e) {
                $this->error('获取公司的排放量失败！' . $e->getMessage());
            }

//        }
    }


    /**
     * 右侧接口
     * @throws \MongoDB\Driver\Exception\Exception
     */
//    public function rightOld()
//    {
//        $param = $this->request->param();
//        $data  = [
//            "before" => [
//                "concentration" => 1,
//                "efficiency" => 1,
//                "slurry" => 1,
//                "pump" => 1
//            ],
//            "plan" => [
//                "concentration" => 1,
//                "efficiency" => 1,
//                "slurry" => 1,
//                "pump" => 1
//            ]
//        ];
//
//        #获取治理设施相关信息
//        $facilityAlias = $this->getFacilityAlias($param['facility_id']);
//        #获取减排时间
//        $times = $this->getControlTime($param['plan_number']);
//
//        #减排前运行浓度
//        $beforeConcentrationService      = new InletFlueGasService;
//        $data['before']['concentration'] = $beforeConcentrationService->getCompanyFacilityOperationConcentration($param['facility_id'], $param['plan_number'], strtoupper($facilityAlias));
//
//        #减排前运行效率
//        $data['before']['efficiency'] = $beforeConcentrationService->getCompanyFacilityOperatingEfficiency($param['facility_id'], $param['plan_number'], strtoupper($facilityAlias));
//
//        #方案值运行浓度和运行效率
//        $tsinghua                       = new TsinghuaDrainEmissionToFacilityParam();
//        $planConcentrationAndEfficiency = $tsinghua->getPlanParamByFacilityId($param['facility_id'], $param['plan_number'], $param['tsinghua_plan_name'], $facilityAlias);
//        $data['plan']['efficiency']     = sprintf('%.3f', $planConcentrationAndEfficiency['efficiency']);
//        $data['plan']['concentration']  = sprintf('%.3f', $planConcentrationAndEfficiency['concentration']);
//
//        #运行浓度和运行效率趋势图
//        $data['trend_concentration'] = $beforeConcentrationService->getCompanyFacilityBeforeOperationConcentration($param['facility_id'], $param['plan_number'], $data['plan']['concentration'], strtoupper($facilityAlias));
//        $data['trend_efficiency']    = $beforeConcentrationService->getCompanyFacilityBeforeOperationEfficiency($param['facility_id'], $param['plan_number'], $data['plan']['efficiency'], strtoupper($facilityAlias));
//
//        #获取脱硫数据
//        if ($facilityAlias == 'SO2') {
//            #减排前供浆量
//            $beforeSulfurSlurryService = new SulfurSlurrySupplyService;
//            $data['before']['slurry']  = $beforeSulfurSlurryService->singleCompanySingleDrainSingleFacility($param['facility_id']);
//
//            #减排前循环泵组合
//            $beforeSulfurPumpService = new SulfurPumpService;
//            $data['before']['pump']  = $beforeSulfurPumpService->singleCompanySingleDrainSingleFacility($param['facility_id']);
//
//            #方案值供浆量和循环泵组合
//            $ws                           = new WorkingModelService;
//            $planSlurrySupplyAndPumpGroup = $ws->forecast($param['company_id'], $param['facility_id'], $times['startTime'], $times['endTime'], $param['plan_number'], $param['tsinghua_plan_name']);
//            $data['plan']['slurry']       = $planSlurrySupplyAndPumpGroup['slurrySupply'] ?? "";
//            $data['plan']['pump']         = $planSlurrySupplyAndPumpGroup['pumpGroup'] ?? "";
//
//            #方案值钙硫比液气比
//            $planCalciumSulfurRatioAndLiquidGasRatio = $this->getPlanCalciumSulfurRatioAndLiquidGasRatio($param['company_id'], $param['facility_id'], $times['startTime'], $times['endTime'], $param['plan_number'], $param['tsinghua_plan_name']);
//
//            #减排前钙硫比趋势图
//            $sulfurCaSRatioService = new SulfurCaSRatioService();
//            $data['trend_ca']      = $sulfurCaSRatioService->singleCompanySingleDrainSingleFacilityDetails($planCalciumSulfurRatioAndLiquidGasRatio['CaSRatio'], $param['plan_number'], $param['facility_id']);
//
//            #减排前液气比趋势图
//            $beforeSulfurLiquidService = new SulfurLiquidGasRatioService();
//            $data['trend_liquid']      = $beforeSulfurLiquidService->singleCompanySingleDrainSingleFacilityDetails($planCalciumSulfurRatioAndLiquidGasRatio['liquidGasRatio'], $param['facility_id'], $param['plan_number']);
//        }
//
//        $this->success('成功', $data);
//    }

    public function right()
    {
        //step1:传参
        $param = $this->request->param();

        //step2:查询
        $where = [
            'plan_number' => $param['plan_number'],
            'tsinghua_plan_name' => $param['tsinghua_plan_name'],
            'facility_id' => $param['facility_id'],
            'company_id' => $param['company_id'],
        ];
        $data  = db::name('control_step_two_get_facility_params')
            ->field('*')
            ->where($where)
            ->find();
        if (empty($data)) {
            $this->error('没有数据');
        }
        $data['before'] = json_decode($data['before'], true);
        $data['plan']   = json_decode($data['plan'], true);

        $data['trend_concentration'] = json_decode($data['trend_concentration'], true);
        $data['trend_efficiency']    = json_decode($data['trend_efficiency'], true);
        $dataNew                     = [];

        //step3:处理数据
        $dataNew['before']['concentration'] = $data['before']['concentration'];
        $dataNew['before']['efficiency']    = $data['before']['efficiency'];
        $dataNew['plan']['concentration']   = $data['plan']['concentration'];
        $dataNew['plan']['efficiency']      = $data['plan']['efficiency'];
        $dataNew['trend_concentration']     = $data['trend_concentration'];
        $dataNew['trend_efficiency']        = $data['trend_efficiency'];
        if ($data['type'] == 'SO2') {
            $data['trend_ca']            = json_decode($data['trend_ca'], true);
            $data['trend_liquid']        = json_decode($data['trend_liquid'], true);
            $dataNew['before']['slurry'] = round($data['before']['slurry'], 2);
            $dataNew['before']['pump']   = $data['before']['pump'];
            $dataNew['plan']['slurry']   = round($data['plan']['slurry'], 2);
            $dataNew['plan']['pump']     = $data['plan']['pump'];
            $dataNew['trend_ca']         = $data['trend_ca'];
            $dataNew['trend_liquid']     = $data['trend_liquid'];
        }
        if (!$data) {
            $this->error('获取数据失败！');
        }
        $this->success('获取数据成功！', $dataNew);
    }

    /**
     * 定时任务执行获取预案设施的参数
     * @return bool
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-08-09
     */
    public function rightAuto()
    {
        $data = [
            "before" => [
                "concentration" => 1,
                "efficiency" => 1,
            ],
            "plan" => [
                "concentration" => 1,
                "efficiency" => 1,
            ]
        ];

        $control                    = new ControlService();
        $company                    = new CompanyService();
        $beforeConcentrationService = new InletFlueGasService;
        $tsinghua                   = new TsinghuaDrainEmissionToFacilityParam();
        $stepTwoRightModel          = new ControlStepTwoGetFacilityParamsModel();

        //step1:发现清单
        $planNumber       = $control->getControlPlanNumber();  //获取今天的预案编号
//        $planList = [
////            'CZ2019-08-12 001号',
//            'CZ2019-08-11 001号',
////            'CZ2019-08-10 001号',
////            'CZ2019-08-09 001号',
////            'CZ2019-08-08 001号',
////            'CZ2019-08-07 001号',
////            'CZ2019-08-06 001号',
////            'CZ2019-08-04 001号',
////            'CZ2019-08-03 001号',
////            'CZ2019-08-02 001号',
////            'CZ2019-08-01 001号',
////            'CZ2019-07-31 001号',
//        ];
//        foreach ($planList as $kk => $vv) {
//            $planNumber       = $vv;
            $existSettingList = $control->findSettingList($planNumber);
            if ($existSettingList == false) {
                return false;
            }

            //step2:获取设施列表,目前只有排口1，将来需要修改 todo
            $faciliyArr = $company->getFacilitiesByDrainId(1);
            foreach ($faciliyArr as $k => $v) {
                $tsinghuaPlanNameList = $control->getPlanTsingNameList($planNumber);
                try {
                    foreach ($tsinghuaPlanNameList as $k2 => $v2) {
                        //step3-1:发现已经有数据
                        $findStepTwoHaveData = $control->findControlStepTwoGetFacilityParams($planNumber, $v['id'], $v2['name']);
                        if ($findStepTwoHaveData == true) {
                            continue;
                        }
                        #获取治理设施相关信息
                        $facilityAlias = $this->getFacilityAlias($v['id']);
                        #获取减排时间
                        $times = $this->getControlTime($planNumber);

                        #减排前运行浓度
                        $data['before']['concentration'] = $beforeConcentrationService->getCompanyFacilityOperationConcentration($v['id'], $planNumber, strtoupper($facilityAlias));

                        #减排前运行效率
                        $data['before']['efficiency'] = $beforeConcentrationService->getCompanyFacilityOperatingEfficiency($v['id'], $planNumber, strtoupper($facilityAlias));

                        #方案值运行浓度和运行效率
                        $planConcentrationAndEfficiency = $tsinghua->getPlanParamByFacilityId($v['id'], $planNumber, $v2['name'], $facilityAlias);
                        $data['plan']['efficiency']     = sprintf('%.3f', $planConcentrationAndEfficiency['efficiency']);
                        $data['plan']['concentration']  = sprintf('%.3f', $planConcentrationAndEfficiency['concentration']);

                        #运行浓度和运行效率趋势图
                        $data['trend_concentration'] = $beforeConcentrationService->getCompanyFacilityBeforeOperationConcentration($v['id'], $planNumber, $data['plan']['concentration'], strtoupper($facilityAlias));
                        $data['trend_efficiency']    = $beforeConcentrationService->getCompanyFacilityBeforeOperationEfficiency($v['id'], $planNumber, $data['plan']['efficiency'], strtoupper($facilityAlias));

                        $dataNew = [];
                        #获取脱硫数据
                        if ($facilityAlias == 'SO2') {
                            #减排前供浆量
                            $beforeSulfurSlurryService = new SulfurSlurrySupplyService;
                            $data['before']['slurry']  = $beforeSulfurSlurryService->singleCompanySingleDrainSingleFacility($v['id'], $planNumber);

                            #减排前循环泵组合
                            $beforeSulfurPumpService = new SulfurPumpService;
                            $data['before']['pump']  = $beforeSulfurPumpService->singleCompanySingleDrainSingleFacility($v['id'], $planNumber);

                            #方案值供浆量和循环泵组合
                            $ws                           = new WorkingModelService;
                            $planSlurrySupplyAndPumpGroup = $ws->forecast(1, $v['id'], $times['startTime'], $times['endTime'], $planNumber, $v2['name']);
                            $data['plan']['slurry']       = isset($planSlurrySupplyAndPumpGroup['slurrySupply']) ? $planSlurrySupplyAndPumpGroup['slurrySupply'] : 0;
                            $data['plan']['pump']         = isset($planSlurrySupplyAndPumpGroup['pumpGroup']) ? $planSlurrySupplyAndPumpGroup['pumpGroup'] : 0;

                            #方案值钙硫比液气比
                            $planCalciumSulfurRatioAndLiquidGasRatio = $this->getPlanCalciumSulfurRatioAndLiquidGasRatio(1, $v['id'], $times['startTime'], $times['endTime'], $planNumber, $v2['name']);

                            #减排前钙硫比趋势图
                            $sulfurCaSRatioService = new SulfurCaSRatioService();
                            $data['trend_ca']      = $sulfurCaSRatioService->singleCompanySingleDrainSingleFacilityDetails($planCalciumSulfurRatioAndLiquidGasRatio['CaSRatio'], $planNumber, $v['id']);

                            #减排前液气比趋势图
                            $beforeSulfurLiquidService = new SulfurLiquidGasRatioService();
                            $data['trend_liquid']      = $beforeSulfurLiquidService->singleCompanySingleDrainSingleFacilityDetails($planCalciumSulfurRatioAndLiquidGasRatio['liquidGasRatio'], $planNumber, $v['id']);

                            //插入数据库
                            $dataNew['trend_ca']     = json_encode($data['trend_ca'], true);
                            $dataNew['trend_liquid'] = json_encode($data['trend_liquid'], true);
                        }

                        $dataNew['type']                = $facilityAlias;
                        $dataNew['company_id']          = 1;
                        $dataNew['facility_id']         = $v['id'];
                        $dataNew['plan_number']         = $planNumber;
                        $dataNew['tsinghua_plan_name']  = $v2['name'];
                        $dataNew['before']              = json_encode($data['before'], true);
                        $dataNew['plan']                = json_encode($data['plan'], true);
                        $dataNew['trend_concentration'] = json_encode($data['trend_concentration'], true);
                        $dataNew['trend_efficiency']    = json_encode($data['trend_efficiency'], true);
                        $stepTwoRightModel->allowField(true)->data($dataNew, true)->isUpdate(false)->save();
                        print "预案编号：" . $planNumber . "-设施ID：" . $v['id'] . "-数据插入数据成功！\n";
                    }
                } catch (\Exception $e) {
                    $this->error('获取数据失败！' . $e->getMessage());
                }
            }
//        }

    }

    /**
     * 获取钙硫比液气比方案值趋势图
     * @param $companyId
     * @param $facilityId
     * @param $startTime
     * @param $endTime
     * @param string $planNumber
     * @param string $tsinghuaPlanName
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getPlanCalciumSulfurRatioAndLiquidGasRatio($companyId, $facilityId, $startTime, $endTime, $planNumber = "", $tsinghuaPlanName = "")
    {
        #获取方案值钙硫比液气比
        $ws                                                        = new WorkingModelService;
        $planCalciumSulfurRatioAndLiquidGasRatio                   = $ws->reaction($companyId, $facilityId, $startTime, $endTime, $planNumber, $tsinghuaPlanName);
        $planCalciumSulfurRatioAndLiquidGasRatio['CaSRatio']       = $planCalciumSulfurRatioAndLiquidGasRatio['CaSRatio'] ?? null;
        $planCalciumSulfurRatioAndLiquidGasRatio['liquidGasRatio'] = $planCalciumSulfurRatioAndLiquidGasRatio['liquidGasRatio'] ?? null;
        #获取减排天数量
        $days = floor(abs((strtotime($startTime) - strtotime($endTime))) / (60 * 60 * 24));
        #组合echart格式
        $data = [
            'CaSRatio' => [],
            'liquidGasRatio' => []
        ];
        for ($i = 0; $i <= $days; ++$i) {
            $data['CaSRatio']['date'][]    = date('m/d', strtotime("+{$i} day", strtotime($startTime)));
            $data['CaSRatio']['data'][0][] = sprintf('%.3f', $planCalciumSulfurRatioAndLiquidGasRatio['CaSRatio']);

            $data['liquidGasRatio']['date'][]    = date('m/d', strtotime("+{$i} day", strtotime($startTime)));
            $data['liquidGasRatio']['data'][0][] = sprintf('%.3f', $planCalciumSulfurRatioAndLiquidGasRatio['liquidGasRatio']);
        }
        return $data;
    }

    /**
     * 获取治理设施别名 SO2/NO2
     * @param $facilityId
     * @return string
     */
    private function getFacilityAlias($facilityId): string
    {
        $sql      = "SELECT `type` FROM `basic_facility` WHERE id = ?";
        $facility = Db::query($sql, array($facilityId));
        if (empty($facility)) {
            $this->error('未知设施');
        }
        $facilityType = $facility[0]['type'];

        $typeAlias = "";
        switch ($facilityType) {
            case 1:
                $typeAlias = "NO2";
                break;
            case 2:
                $typeAlias = "SO2";
                break;
        }

        return $typeAlias;
    }

    /**
     * 通过预案号获取管控前七天
     * @param $planNumber
     * @return array
     */
    private function getControlTime($planNumber): array
    {
        $sql         = "SELECT `control_start_time`, `control_end_time` FROM `control_plan_name` WHERE `plan_number` = ? ";
        $controlTime = Db::query($sql, array($planNumber));
        if (empty($controlTime)) {
            $this->error('未知预案号!');
        }
        $controlStartTime = strtotime($controlTime[0]['control_start_time']);
        $result           = [
            'startTime' => date('Ymd', strtotime('-8 day', $controlStartTime)),
            'endTime' => date('Ymd', strtotime('-2 day', $controlStartTime)),
        ];

        return array_merge($result, $controlTime[0]);
    }
}